from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings
from rest_framework.generics import CreateAPIView

from oauth.exceptions import OAuthQQAPIError
from oauth.models import OAuthQQUser
from oauth.serializers import OAuthQQUserSerializer
from oauth.utils import OAuthQQ
from carts.utils import merge_cart_cookie_to_redis


# Create your views here.

# get r'^qq/authorization/$'
class QQAuthURLView(APIView):
    """
    获取QQ登录的url
    """

    def get(self, request):
        """
        获取返回给前端的QQ登录url
        :param request:
        :return:
        """
        next = request.query_params.get('next')
        oauth_qq = OAuthQQ(state=next)
        login_url = oauth_qq.get_qq_login_url()
        return Response({'login_url': login_url})


# url r'^qq/user/$'
# 添加post方法, 添加模型用到CreateAPIView
class QQAuthUserView(CreateAPIView):
    """
    QQ登陆的用户
    """
    serializer_class = OAuthQQUserSerializer

    def get(self, request):
        """
        获取QQ登陆的用户信息
        :param request:
        :return:
        """
        # 1 获取code
        code = request.query_params.get("code")
        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)
        # 2 根据code获取access_token
        oauth_qq = OAuthQQ()
        try:
            access_token = oauth_qq.get_access_token(code)
            # 3 根据access_token获取用户openid
            openid = oauth_qq.get_openid(access_token)
        except OAuthQQAPIError:
            return Response({'message': '获取数据失败'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 4 拿着openid查询数据库
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 第一次登陆
            access_token = oauth_qq.generate_save_user_token(openid)
            return Response({'access_token': access_token})

        else:
            user = oauth_qq_user.user
            # 补充生成记录登录状态的token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            # 保存进返回给前端user中
            user.token = token

            response = Response({
                'username': user.username,
                'user_id': user.id,
                'token': token
            })

            # 合并购物车
            merge_cart_cookie_to_redis(request, user, response)

            return response

    def post(self, request, *args, **kwargs):
        """
        1 获取参数
        2 校验参数
        3 查看用户是否存在 存在绑定用户, 创建 OAuthQQUser
        4 如果不存 先创建user数据, 创建 OAuthQQUser
        5 签发token
        6 return 数据
        :param request:
        :return:
        """
        response = super().post(request, *args, **kwargs)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request, self.user, response)
        return response



